
import random
import subprocess

import requests
from pip._internal import commands, main

from Include.html_analysis import Html_Analysis



class Download():

    def __init__(self,avurl="",req_url=None):
        #from Include.html_analysis import html_analysis.html
        #self.b=b
        self.req_url=req_url
        ##随机产生一个尾号防止被识别
        self.User_Agent=r"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537."+str(random.randint(10,100))
        self.getHtmlHeaders = {
                          "Range": "0-99999999",
                          "Referer": avurl,
                          "Sec-Fetch-Mode": "cors",
                          "User-Agent": self.User_Agent}
        ##B站传输视频是m4s是一段一段传输 可以利用B站服务器的防崩溃，申请很大的字节，服务器会自动转化为最大字节

    def download(self):
        with open("爬虫视频.mp4", "wb") as f:
            print(self.req_url[0])
            f.write(requests.get(url=self.req_url[0], headers=self.getHtmlHeaders, stream=True, verify=True).content)
            f.close()
        with open("爬虫声音.mp3", "wb") as f:
            if(len(self.req_url)==1):
                return
            f.write(requests.get(url=self.req_url[1], headers=self.getHtmlHeaders, stream=True, verify=True).content)
            f.close()
        #self.video_add_mp3()   ##ffmpeg合成视频太慢 先不合成视频

    def jpg_download(self,my_url=""):
        ua_headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}
        req=self.b.ori_html
        req=req[:(req.find("jpg")+3)]
        req=req[req.find('''content="http:''')+9:]
        with open("封面.jpg","wb")as f:
            f.write(requests.get(url=req, headers=ua_headers).content)

    def video_add_mp3(self):
        subprocess.call(r"D:\游览器下载\ffmpeg-20190805-5ac28e9-win64-static\bin\ffmpeg -i 爬虫声音.mp3  -i 爬虫视频.mp4 out.mp4",shell=True)

    def DanMu_download(self):
            # 弹幕下载还未完成

            headers = {
                "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
                "Accept-Encoding": "gzip, deflate, br",
                "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
                "Host": "api.bilibili.com",
                "Referer": "https://www.bilibili.com/",
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.33",
            }
            api_url = "https://api.bilibili.com/x/v1/dm/list.so?oid=109071945"
            res = requests.get(api_url, headers=headers)
            with open("弹幕.txt", "wb")as f:
                f.write(res.content)

